import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import model.OpsviewVersion;

import org.apache.http.HttpResponse;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.JSONParser;

public class OpsviewHandler {
	private static OpsviewHandler instance = null;
	private static String username = null;
	private static String token = null;
	private Properties prop;

	// Singleton
	private OpsviewHandler() {
		//토큰정보가 없으면 새로 입력받음
		if (!tokenCheck()) {
			System.err.println("no token");
			URI uri;
			try {
				uri = URIUtils.createURI("http", "www.creativedeveloper.pe.kr",
						3000, "/rest/login", null, null);
				List<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
				parameters.add(new BasicNameValuePair("username", Constants
						.getUsername()));
				parameters.add(new BasicNameValuePair("password", Constants
						.getPassword()));
				UrlEncodedFormEntity reqEntity = new UrlEncodedFormEntity(
						parameters);

				HttpPost post = new HttpPost(uri);
				post.setEntity(reqEntity);

				DefaultHttpClient httpclient = new DefaultHttpClient();
				HttpResponse response = httpclient.execute(post);

				Reader reader = new InputStreamReader(response.getEntity()
						.getContent());

				Object temp = JSONValue.parse(reader);
				HashMap map = (HashMap) temp;

				token = (String) map.get("token");

				File file = new File("token.properties");
				FileWriter fw = new FileWriter(file);

				fw.write("username:" + Constants.getUsername());
				fw.write("\n");
				fw.write("token:" + token);
				fw.close();

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			Constants.USERNAME = (String) prop.get("username");
			token = prop.getProperty("token");
		}
	}

	// 토큰 파일에 있는지 확인
	private boolean tokenCheck() {
		boolean hasToken = false;
		File file = new File("token.properties");

		if (file.canRead()) {
			try {
				FileInputStream reader = new FileInputStream(file);
				prop = new Properties();
				prop.load(reader);

				token = (String) prop.get("token");

				if (!token.toString().equals("null")) {
					hasToken = true;
				}

			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return hasToken;
	}

	public static OpsviewHandler getHandler() {

		if (instance == null)
			instance = new OpsviewHandler();

		return instance;
	}

	public HashMap getVersion() {
		HashMap map = null;
		URI uri;
		try {
			uri = URIUtils.createURI("http", "www.creativedeveloper.pe.kr",
					3000, "/rest", null, null);

			HttpGet get = new HttpGet(uri);
			get.addHeader("Accept", "application/json");

			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(get);

			Reader reader = new InputStreamReader(response.getEntity()
					.getContent());

			Object temp = JSONValue.parse(reader);
			map = (HashMap) temp;
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	public HashMap reload() {
		URI uri;
		HashMap map = null;
		try {
			uri = URIUtils.createURI("http", "www.creativedeveloper.pe.kr",
					3000, "/rest/reload", null, null);

			HttpGet get = new HttpGet(uri);
			get.addHeader("X-Opsview-Username", Constants.USERNAME);
			get.addHeader("X-Opsview-Token", token);
			get.addHeader("Accept", "application/json");

			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(get);

			Reader reader = new InputStreamReader(response.getEntity()
					.getContent());

			Object temp = JSONValue.parse(reader);
			map = (HashMap) temp;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	public HashMap getServerInfo() {
		URI uri;
		HashMap map = null;
		try {
			uri = URIUtils.createURI("http", "www.creativedeveloper.pe.kr",
					3000, "/rest/serverinfo", null, null);

			HttpGet get = new HttpGet(uri);
			get.addHeader("X-Opsview-Username", Constants.USERNAME);
			get.addHeader("X-Opsview-Token", token);
			get.addHeader("Accept", "application/json");

			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(get);

			Reader reader = new InputStreamReader(response.getEntity()
					.getContent());

			Object temp = JSONValue.parse(reader);
			map = (HashMap) temp;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	public HashMap getInfo() {
		URI uri;
		HashMap map = null;
		try {
			uri = URIUtils.createURI("http", "www.creativedeveloper.pe.kr",
					3000, "/rest/info", null, null);

			HttpGet get = new HttpGet(uri);
			get.addHeader("X-Opsview-Username", Constants.USERNAME);
			get.addHeader("X-Opsview-Token", token);
			get.addHeader("Accept", "application/json");

			DefaultHttpClient httpclient = new DefaultHttpClient();
			HttpResponse response = httpclient.execute(get);

			Reader reader = new InputStreamReader(response.getEntity()
					.getContent());

			Object temp = JSONValue.parse(reader);
			map = (HashMap) temp;

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return map;
	}

	public static void main(String[] args) {
		
		//핸들러 생성
		OpsviewHandler opsview = OpsviewHandler.getHandler();
		
		OpsviewVersion version = new OpsviewVersion();
		HashMap v = opsview.getVersion();
		
	}

}
